package com.yc.thread.pro1_matrix.group;

import com.yc.thread.pro1_matrix.individual.individualMultiplierTask;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zwei
 * @create 2024-07-17 19:08
 */
public class ParallelGroupMultiplier {
    public static void multiplt(double [][] matrix1,double [][] matrix2,double [][] result){
        List<Thread>threads=new ArrayList<>();
        int row1=matrix1.length;    //第一个矩阵的行数
        int column1=matrix1[0].length;  //第一个矩阵的列数

        int row2=matrix2.length;    //第二个矩阵的行数
        int column2=matrix2[0].length;  //第二个矩阵的列数
        //获取cpu的核数
        Runtime r=Runtime.getRuntime(); //静态单例模型-》Runtime代表当前运行的jvm环境
        int numThreads=r.availableProcessors();
        System.out.println("cpu核数："+numThreads);
        //计算每个线程要执行运算的行的起始和结束
        int startIndex,endIndex,step;
        step=row1/numThreads;
        startIndex=0;
        endIndex=step;
        //循环numThreads次，每次启动一个线程  指定此线程运行的范围
        for (int i = 0; i < numThreads; i++) {
            //启动任务
            GroupMultiplierTask gmt = new GroupMultiplierTask(result, matrix1, matrix2, startIndex, endIndex);
            Thread t = new Thread(gmt);
            t.start();
            threads.add(t);
            //更新startIndex和endIndex
            startIndex = endIndex;
            endIndex = endIndex + step;
            //处理最后一组

            if(i==numThreads-2){        //或者endIndex=   i==numThreads-2?  row1:endIndex+step;
                endIndex=row1;
            }
            System.out.println("第"+i+"个线程的起始位置："+startIndex+"，结束位置："+endIndex);
        }
        for (Thread t:threads){
            try {
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
